package com.di.base.controller;

import com.alibaba.fastjson.JSON;
import com.di.base.common.dto.StorageRequestDTO;
import com.di.base.feign.StorageFeignClient;
import com.di.base.proxy.OrderSagaService;
import com.di.base.service.OrderTblService;
import io.seata.saga.engine.StateMachineEngine;
import io.seata.saga.statelang.domain.ExecutionStatus;
import io.seata.saga.statelang.domain.StateMachineInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderTblController {

    // 注入 Seata Saga 状态机引擎
    @Autowired
    private StateMachineEngine stateMachineEngine;

    @Resource
    StorageFeignClient storageFeignClient;
    /**
     * 启动 Saga 模式的订单创建流程
     * @param userId 用户ID
     * @param productId 产品ID
     * @param count 数量
     * @param amount 金额
     * @return 执行结果
     */

    /**
     * 启动 Saga 模式的订单创建流程 (使用固定参数)
     * @return 执行结果
     */
    @GetMapping("/createSaga")
    public String createOrderSaga() { // 移除了 @RequestParam 参数

        try {
            Map<String, Object> startParams = new HashMap<>();
            // 1. 准备启动状态机所需的固定参数
//            startParams.put("userId", "U1003");        // 账户余额充足
            startParams.put("userId", "U1002");        // 账户余额不够
            startParams.put("productId", "P10001");
            startParams.put("count", 2);
            startParams.put("amount", 100.0);

            log.info("使用固定参数启动Saga流程: userId=1, productId=1, count=2, amount=100.0");

            StorageRequestDTO storageRequestDTO = new StorageRequestDTO();
            storageRequestDTO.setProductId(startParams.get("productId").toString());
            storageRequestDTO.setCount(startParams.containsKey("count") ? Integer.valueOf(startParams.get("count").toString()) : 1);
            // 2. 调用状态机引擎启动执行
            // 第一个参数是状态机名称，必须与 business_process.json 中的 Name 一致
            // 第二个参数是 businessKey，可以为空，用于标识这次执行实例
//            StateMachineInstance instance = stateMachineEngine.start("createOrderStateMachine", null, startParams);
            StateMachineInstance instance = stateMachineEngine.start("createOrderStateMachine-demo", null, startParams);

            // 3. 检查执行结果
            if (ExecutionStatus.SU.equals(instance.getStatus())) {
                return "Saga流程执行成功！状态机实例ID: " + instance.getId();
            } else {
                // 执行失败或异常
                return "Saga流程执行失败，状态: " + instance.getStatus() +
                        ", 错误信息: " + JSON.toJSONString(instance.getException());
            }
        } catch (Exception e) {
            log.error("启动Saga流程异常", e);
            throw new RuntimeException("启动Saga流程异常: " + e.getMessage());
        }
    }

}